<?php
namespace common\components;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;

/**
 * Class Upload
 * 上传文件组件
 */
class Upload extends \yii\base\Component
{
    public static $mutidi = '|';
    public static $errmsg = '';
    public static $noimg = '/static/images/noimage.jpg';

    public static function upload($model, $name = 'thumb',$type='images',$ismuti=true)
    {

        $imgs = UploadedFile::getInstances($model, $name);
        if ($imgs) {
            $mutipath = [];
            foreach ($imgs as $key => $img){

                $thumbname = md5(time() . $img->baseName) . '.' . $img->extension;
//                $path = $type.'/'.date("Ymd") . '/';
                $path = $type.'/'.date("Ymw") . '/';
                $uploaddir = \Yii::getAlias('@uploadpath') . '/' . $path;
                if (!is_dir($uploaddir)) {
                    if (!mkdir($uploaddir, 0777, true)) {
                        die('创建目录失败...');
                    } else {
                        chmod($uploaddir, 0777);
                    }
                }

                $img->saveAs($uploaddir . $thumbname);
                if($error = $img->getHasError()){
                    self::getErrors($error);
                }
                $mutipath[] = $path . $thumbname;
            }

            if(!$ismuti){       //只上传单图
               return $path . $thumbname;
            }

            if($model->scenario == 'update'){
                if(!empty($model->getoldAttribute($name))){
                    return implode(self::$mutidi,$mutipath).self::$mutidi.$model->getoldAttribute($name);
                }
            }

            //删除原来的图片
//            self::deleteImg($model,$name);
            return implode(self::$mutidi,$mutipath);
        }
        return false;
    }



    public static function uploadByName($name = 'thumb',$type='images',$ismuti=true)
    {

        $imgs = UploadedFile::getInstancesByName($name);
        var_dump($imgs);
        if ($imgs) {
            $mutipath = [];
            foreach ($imgs as $key => $img){

                $thumbname = md5(time() . $img->baseName) . '.' . $img->extension;
//                $path = $type.'/'.date("Ymd") . '/';
                $path = $type.'/'.date("Ymw") . '/';
                $uploaddir = \Yii::getAlias('@uploadpath') . '/' . $path;
                if (!is_dir($uploaddir)) {
                    if (!mkdir($uploaddir, 0777, true)) {
                        die('创建目录失败...');
                    } else {
                        chmod($uploaddir, 0777);
                    }
                }

                $img->saveAs($uploaddir . $thumbname);
                if($error = $img->getHasError()){
                    self::getErrors($error);
                }
                $mutipath[] = $path . $thumbname;
            }

            if(!$ismuti){       //只上传单图
                return $path . $thumbname;
            }

            //删除原来的图片
            return implode(self::$mutidi,$mutipath);
        }
        return false;
    }



    public static function uploadBase64($img,$di='%^')
    {

        $imgs = explode($di,$img);
        if(strpos($img,$di)){
            $imgs = explode($di,$img);
            foreach ($imgs as $key => $row){
                $res[] = self::upload64($row);
            }
            return $res;
        }

        return self::upload64($img);
    }


    /**
     * @param $img
     * @return bool|string
     * base64位图片方式上传
     */
    public static function upload64($img)
    {
        $img = str_replace(['data:image/jpeg;base64,','data:image/png;base64,'], '', $img);
        $data = base64_decode($img);

        //名称
        $imgname = md5(rand(1, 100).time()) . '.jpg';

        //路径
        $path = 'images/'.date("Ymd") . '/';
        $uploaddir = \Yii::getAlias('@uploadpath') . '/' . $path;

        if(!is_dir($uploaddir)){
            self::createDirs($uploaddir);
        }

        $imgPath = $uploaddir.$imgname;
        //存储
        if(file_exists($imgPath)){
            unlink($imgPath);
        }
        $fp = fopen($imgPath,'w');
        $result = fwrite($fp,$data);
        fclose($fp);
        if($result){
            return $path.$imgname;
        }
        return false;
    }


    /**
     * @param null $model
     * @param string $field
     * @param bool $shownoimg
     * @return string
     * 获取上传图片的地址
     */
    public static function UploadUrl($model=null,$field='thumb',$shownoimg = true)
    {
        if($model instanceof ActiveRecord){
            if(empty($model->getAttribute($field))){      //没有图片，展示默认的图片
                if(!$shownoimg){
                    return '';
                }
                return \Yii::getAlias('@web').'/static/images/noimage.jpg';
            }
            return \Yii::getAlias('@uploadurl').'/'.$model->getAttribute($field);
        }else{
            if(empty($model)){
                if(!$shownoimg){
                    return '';
                }
                return \Yii::getAlias('@web').'/static/images/noimage.jpg';
            }
            return \Yii::getAlias('@uploadurl').'/'.$model;
        }
    }


    /**
     * @param $model
     * @param $filed
     * 删除图片
     */
    public static function deleteImg($model,$filed='thumb')
    {
        $path = self::checkGetPath($model,$filed);
        $res = false;
        if(is_array($path)){
            foreach($path as $key => $row){
                if(is_file($row)){
                    $res = unlink($row);
                }
            }
        }else{
            if(is_file($path)){
                $res = unlink($path);
            }
        }

        return $res;
    }



    /**
     * @param $model
     * @return string
     * 获取图片的路径统一调用入口
     */
    public static function checkGetUrl($model,$muti=false,$field='thumb',$shownoimg = true)
    {

        //是否多张图
        if(strpos($model,self::$mutidi) !== false) {
            return self::opMutil($model,$muti,$field);
        }

        //本地一张图片，处理返回
        if(is_string($model) && (strpos($model,"http://")!==false || strpos($model,"https://")!==false)) {
            if($muti){      //想去多张，但只有一张，给出一个数组
                return [$model];
            }
            return $model;
        }

        if($muti){      //想取多张，但只有一张，给出一个数组
            if(!$shownoimg && empty(self::UploadUrl($model,$field,$shownoimg))){
                return [];
            }
            return [self::UploadUrl($model,$field,$shownoimg)];
        }

        return self::UploadUrl($model,$field,$shownoimg);
    }


    /**
     * @param $model
     * @param $muti
     * @param $field
     * @return array|string
     * 处理多图
     */
    public static function opMutil($model,$muti,$field)
    {
        $model = explode(self::$mutidi, $model);
        //多图取出其中第一个
        if (!$muti) {
            if(is_string($model[0]) && (strpos($model[0],"http://")!==false || strpos($model[0],"https://")!==false)) {
                return $model[0];
            }
            return self::UploadUrl($model[0], $field);
        }
        //取出全部的
        $img = [];
        foreach ($model as $key => $row){
            if(is_string($row) && (strpos($row,"http://")!==false || strpos($row,"https://")!==false)) {
                $img[] = $row;
            }else{
                $img[] = self::UploadUrl($row, $field);
            }
        }
        return $img;

    }


    /**
     * @param null $model
     * @param string $field
     * @return string
     * 获取物理路径
     */
    public static function checkGetPath($model=null,$field='thumb')
    {
        if($model instanceof ActiveRecord){
            if(strpos($model->getAttribute($field),self::$mutidi) !== false) {
                $img = explode(self::$mutidi,$model->getAttribute($field));
                foreach ($img as $key => $row){
                    $result[] = str_replace('\\','/',\Yii::getAlias('@uploadpath').'/'.$row);
                }
                unset($img);
                return $result;
            }
            return [str_replace('\\','/',\Yii::getAlias('@uploadpath').'/'.$model->getAttribute($field))];
        }else{
            if(strpos($model,self::$mutidi) !== false) {
                $img = explode(self::$mutidi,$model);
                foreach ($img as $key => $row){
                    $result[] = str_replace('\\','/',\Yii::getAlias('@uploadpath').'/'.$row);
                }
                unset($img);
                return $result;
            }
            return str_replace('\\','/',\Yii::getAlias('@uploadpath').'/'.$model);
        }

    }


    /**
     * @param $dir
     * @return bool
     * 创建目录
     */
    public static function createDirs($dir)
    {
        return  is_dir ( $dir ) or self::createDirs(dirname( $dir )) and  mkdir ( $dir , 0777);
    }


    /**
     * @param $error
     * @return string
     * 获取错误信息
     */
    public static function getErrors($error)
    {
        switch($error) {
            case 1:
                // 文件大小超出了服务器的空间大小
                self::$errmsg = "文件大小超出了服务器的空间大小";
                break;
            case 2:
                // 要上传的文件大小超出浏览器限制
                self::$errmsg = "要上传的文件大小超出浏览器限制";
                break;

            case 3:
                // 文件仅部分被上传
                self::$errmsg = "文件仅部分被上传";
                break;

            case 4:
                // 没有找到要上传的文件
                self::$errmsg = "没有找到要上传的文件";
                break;

            case 5:
                // 服务器临时文件夹丢失
                self::$errmsg = "服务器临时文件夹丢失";
                break;

            case 6:
                // 文件写入到临时文件夹出错
                self::$errmsg = "文件写入到临时文件夹出错";
                break;
            default:
                break;
        }
        return self::$errmsg;
    }




    public static function initialPreviewConfig($model,$field='thumb',$table='',$id=0,$idname='id',$type='image',$filetype="video/mp4")
    {

        $attchs = self::checkGetPath($model,$field);

        if($attchs && is_array($attchs)){
            foreach ($attchs as $key => $row){

                $data[] = [
                    'type' =>$type,
                    'width' => '120px',
                    'caption' => $row,
                    'url' => '/site/attr-delete?path='.$row,
                    'key' => $key+1,
                    'extra' => ['id' =>$id,'table'=>$table,'field'=>$field,'idname'=>$idname],
                    'filetype'=>$filetype
                ];
            }
        }
        return $data;
    }





}



?>